import React, { createContext, useContext, useReducer, ReactNode } from 'react';

import { Website } from '../data/config';

// 状态类型定义
export interface AppState {
  // 搜索和筛选
  searchQuery: string;
  activeCategory: string;
  
  // UI 状态
  isLoading: boolean;
  
  // 数据状态
  filteredWebsites: Website[];
  
  // 未来扩展预留
  favorites: number[];
  searchHistory: string[];
}

// Action 类型定义
export type AppAction = 
  | { type: 'SET_SEARCH_QUERY'; payload: string }
  | { type: 'SET_ACTIVE_CATEGORY'; payload: string }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_FILTERED_WEBSITES'; payload: Website[] }
  | { type: 'RESET_FILTERS' }
  | { type: 'ADD_TO_FAVORITES'; payload: number }
  | { type: 'REMOVE_FROM_FAVORITES'; payload: number }
  | { type: 'ADD_SEARCH_HISTORY'; payload: string };

// 初始状态
export const initialState: AppState = {
  searchQuery: '',
  activeCategory: 'all',
  isLoading: false,
  filteredWebsites: [],
  favorites: [],
  searchHistory: [],
};

// Reducer 函数
export const appReducer = (state: AppState, action: AppAction): AppState => {
  switch (action.type) {
    case 'SET_SEARCH_QUERY':
      return {
        ...state,
        searchQuery: action.payload,
      };
    
    case 'SET_ACTIVE_CATEGORY':
      return {
        ...state,
        activeCategory: action.payload,
      };
    
    case 'SET_LOADING':
      return {
        ...state,
        isLoading: action.payload,
      };
    
    case 'SET_FILTERED_WEBSITES':
      return {
        ...state,
        filteredWebsites: action.payload,
      };
    
    case 'RESET_FILTERS':
      return {
        ...state,
        searchQuery: '',
        activeCategory: 'all',
      };
    
    case 'ADD_TO_FAVORITES':
      return {
        ...state,
        favorites: [...state.favorites, action.payload],
      };
    
    case 'REMOVE_FROM_FAVORITES':
      return {
        ...state,
        favorites: state.favorites.filter(id => id !== action.payload),
      };
    
    case 'ADD_SEARCH_HISTORY':
      const newHistory = [action.payload, ...state.searchHistory.filter(item => item !== action.payload)].slice(0, 10);
      return {
        ...state,
        searchHistory: newHistory,
      };
    
    default:
      return state;
  }
};

// Context 类型定义
interface AppContextType {
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
}

// 创建 Context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider 组件
interface AppProviderProps {
  children: ReactNode;
}

export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

// 自定义 Hook
export const useAppContext = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
};

// 便捷的 Action Hooks
export const useAppActions = () => {
  const { dispatch } = useAppContext();

  return {
    setSearchQuery: (query: string) => {
      dispatch({ type: 'SET_SEARCH_QUERY', payload: query });
      if (query.trim()) {
        dispatch({ type: 'ADD_SEARCH_HISTORY', payload: query.trim() });
      }
    },
    
    setActiveCategory: (category: string) => {
      dispatch({ type: 'SET_ACTIVE_CATEGORY', payload: category });
    },
    
    setLoading: (loading: boolean) => {
      dispatch({ type: 'SET_LOADING', payload: loading });
    },
    
    setFilteredWebsites: (websites: Website[]) => {
      dispatch({ type: 'SET_FILTERED_WEBSITES', payload: websites });
    },
    
    resetFilters: () => {
      dispatch({ type: 'RESET_FILTERS' });
    },
    
    toggleFavorite: (websiteId: number, isFavorite: boolean) => {
      if (isFavorite) {
        dispatch({ type: 'REMOVE_FROM_FAVORITES', payload: websiteId });
      } else {
        dispatch({ type: 'ADD_TO_FAVORITES', payload: websiteId });
      }
    },
  };
};